<script setup lang="ts">
import {reactive, ref, onMounted, nextTick} from 'vue'
import tableList from "@/components/tableList/tableList.vue";
import {useRouter} from 'vue-router'
import {Dialog} from "@/components/Dialog";
import SearchForm from "@/views/student-manage/component/SearchForm.vue";
import Drawer from "@/views/student-manage/component/Drawer.vue";
import {useCommon} from '@/hooks/web/useCommon'
import {commonList,updateTeacher} from "@/api/commonality";
import {ElMessage} from "element-plus";
import {useStorage} from "@/hooks/web/useStorage";
const {getStorage, setStorage, removeStorage} = useStorage()

const {
  teacherOptions,
  getTeacher,
  handleChange,
  pageData,
  projectTree,
  relTeacherOpt,
  getProjectTree
} = useCommon()

onMounted(() => {
  let searchStorage = getStorage('commonalityForm');
  let flag = getStorage('commonalityFlag')
  if (flag && searchStorage) {
    pageData.currentPage = searchStorage.page
    pageData.pageSize = searchStorage.limit
    searchRef.value.searchForm = Object.assign(searchRef.value.searchForm, searchStorage)
  } else {
    removeStorage('commonalityForm')
  }
  fetchData()
  getTeacher()
  getProjectTree()
})

onBeforeUnmount(() => {
  removeStorage('commonalityFlag')
})

let teacherForm = reactive({
  teacher_id: '',
  project_id: '',
  student_ids: []
})
let loading = ref(false)
let drawerVisit = ref('')
let teacherRef = ref('')
const router = useRouter()
let drawerVisible = ref(false)
let tableData = ref([])
let saveLoading = ref(false)
let teacherVisible = ref(false)
const tableHeader = reactive([
  {
    label: '系统时间', prop: 'created_time', width: '170px',type:'html', code: (row) => {
      if (row.created_change == 1) {
        return '<span style="color: #F56C6C">' + row.created_time + '</span>'
      } else {
        return '<span style="color: #67C23A">' + row.created_time + '</span>'
      }
    }
  },
  {
    label: '学生姓名', prop: 'realname', type: 'btn', method: (row) => {
      handleDetail(row)
    }
  },
  {label: '学位项目', prop: 'project', link: 'project_id'},
  {label: '入学时间', prop: 'ruxue', link: 'ruxue'},
  {label: '意向类型', prop: 'yixiang'},
  {label: '当前状态', prop: 'status'},
  {label: '录入人', prop: 'luru', width: '90px'},
  {label: '招生老师', prop: 'zixun', width: '90px'},
  {label: '合作人', prop: 'hezuoren', width: '90px'},
  {label: '学生来源', prop: 'laiyuan'},
  {label: '来源详情', prop: 'laiyuan_xiangqing', type: 'text'},
  {
    label: '回访状态', prop: 'callback_str', width: '100px', type: 'html', code: (row) => {
      if (row.callback_str === '已回访') {
        return '<span style="color: #67C23A">已回访</span>'
      } else {
        return '<span style="color: #F56C6C">未回访</span>'
      }
    }
  },
  {
    label: '历史记录', list: '', default: '历史记录', width: '115px', type: 'btn', method: (row) => {
      handleHistory(row)
    }
  }
])
const tableOptions = reactive({
  label: '操作',
  width: '100px',
  value: 0,
  options: [
    {
      label: '绑定',
      key: 0,
      type: 'text',
      show: (row) => {
        return !row.teacher_id
      },
      method: (row) => {
        handleBinding(row)
      }
    },
    {
      label: '换绑',
      key: 0,
      type: 'text',
      show: (row) => {
        return row.teacher_id
      },
      method: (row) => {
        handleBinding(row)
      }
    },
    // {
    //   label: '已绑定',
    //   key: 0,
    //   type: 'text',
    //   icon: 'el-icon-circle-check',
    //   method: (row) => {
    //   }
    // }
  ]
})

const onSearch = () => {
  pageData.currentPage = 1
  fetchData();
}


const handleClose = () => {
  teacherVisible.value = false
  teacherRef.value.resetFields()
}


const handleBinding = async (row) => {
  if (row === 'batch') {
    if (!batchList.value.length) return ElMessage({type: 'warning', message: '请选择需要绑定/换绑的数据'})
    teacherVisible.value = true
    teacherForm.student_ids = batchList.value
  } else {
    teacherVisible.value = true
    nextTick(() => {
      teacherForm.student_ids = [row.student_id]
      teacherForm.teacher_id = row.teacher_id
    })
  }
}

const handleHistory = async (row) => {
  console.log(row)
  drawerVisible.value = true
  drawerVisit.value.student = Object.assign(drawerVisit.value.student, {
    name: row.realname,
    school: row.school_name,
    student_id: row.id
  })
  drawerVisit.value.getVisit()

}

const handleDetail = async (row) => {
  setStorage('commonalityForm', searchRef.value.searchForm)
  router.push({path: '/commonality/info', query: {student_id: row.student_id, flag: 'commonalityFlag'}})
}

const handlePageChange = (param) => {
  pageData.pageSize = param.limit
  pageData.currentPage = param.page
  fetchData()
}

let batchList = ref([])
const handleSelectChange = (vals) => {
  batchList.value = []
  vals.map(v => {
    batchList.value.push(v.id)
  })
}

let searchRef = ref('')
const fetchData = async () => {
  let params = searchRef.value.searchForm
  params.page = pageData.currentPage
  params.limit = pageData.pageSize
  loading.value = true
  let res = await commonList(params)
  loading.value = false
  if (res) {
    tableData.value = res.data.list
    pageData.total = res.data.page.amount
  }
}

const handleSubmit = async () => {
  let res = await updateTeacher(teacherForm)
  if (res) {
    ElMessage({message: '绑定成功', type: 'success'})
    handleClose()
    await fetchData();
  }
}

const handleCancle = async () => {
  drawerVisible.value = false
}

</script>
<template>
  <el-row>
    <el-col :span="24">
      <search-form :teacher-options="teacherOptions" ref="searchRef" @onSearch="onSearch">
        <template v-slot:operationBtn>
          <el-button type="primary" plain
                     @click="handleBinding('batch')"
                     icon="SetUp"
          >批量绑定 / 换绑
          </el-button>
        </template>
      </search-form>
    </el-col>
    <el-col :span="24" v-loading="loading">
      <tableList :table-data="tableData"
                 :page-data="pageData"
                 :table-header="tableHeader"
                 :table-options="tableOptions"
                 :selection="true"
                 @handlePageChange="handlePageChange"
                 @handleSelectChange="handleSelectChange"
      ></tableList>
    </el-col>
  </el-row>
  <Drawer v-model:drawerVisible="drawerVisible" @cancelClick="handleCancle" ref="drawerVisit"/>
  <Dialog :title="'绑定老师'" :model-value="teacherVisible" @handle-close="handleClose" :max-height="'300px'">
    <el-form label-position="top" ref="teacherRef" :model="teacherForm">
      <el-form-item label="选择院校/项目" prop="teacher_id">
        <el-cascader
            clearable
            @change="handleChange"
            :props="{emitPath:false}"
            v-model="teacherForm.project_id"
            :options="projectTree"
            ref="cascader"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="请选择要绑定的招生老师" prop="teacher_id">
        <el-radio-group v-model="teacherForm.teacher_id">
          <el-radio v-for="item in relTeacherOpt" :label="item.id">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button type="primary" plain @click="handleSubmit" :loading="saveLoading">确定</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="less">
/deep/ .el-input-form {
  .el-input {
    width: 192px;
  }
}

</style>